/*
 * Licensed to the 南京汇海交通科技有限公司
 *
 * Copyright (c) 2025.
 * All rights reserved.
 *
 * 本软件属南京汇海交通科技有限公司所有，在未获得南京汇海交通科技有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.chframework.boot.web.servlets;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

@Slf4j
public class DefaultServlet extends HttpServlet {

    private ConcurrentHashMap<String, String> initParamMap;

    public DefaultServlet(ExecutorService asyncExecutor) {
        initParamMap = new ConcurrentHashMap<>();
        AsyncTask.setAsyncExecutor(asyncExecutor);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init() throws ServletException {
        String[] stackTraceArray = Arrays.stream(Thread.currentThread().getStackTrace())
                .map(StackTraceElement::toString)
                .toArray(String[]::new);
        log.debug("DefaultFilter.init\r\n\r\tat {}", String.join("\r\n\r\tat ", stackTraceArray[1]));

        ServletConfig servletConfig = this.getServletConfig();
        Enumeration<String> initParamNameSet = servletConfig.getInitParameterNames();
        while (initParamNameSet.hasMoreElements()) {
            String initParamName = initParamNameSet.nextElement();
            initParamMap.put(initParamName, servletConfig.getInitParameter(initParamName));
        }
        log.debug("servlet init param - {}", initParamMap);

        AsyncTask.setInitParamMap(initParamMap);
        AsyncTask.createTaskHandler().start();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.isAsyncSupported()) {
            AsyncTask.delayHandler(req, resp, HttpMethod.GET);
        } else {
            resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
            resp.setStatus(HttpStatus.OK.value());
            resp.getWriter().write("default action for GET");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.isAsyncSupported()) {
            AsyncTask.delayHandler(req, resp, HttpMethod.POST);
        } else {
            resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
            resp.setStatus(HttpStatus.OK.value());
            resp.getWriter().write("default action for POST");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.isAsyncSupported()) {
            AsyncTask.delayHandler(req, resp, HttpMethod.PUT);
        } else {
            resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
            resp.setStatus(HttpStatus.OK.value());
            resp.getWriter().write("default action for PUT");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.isAsyncSupported()) {
            AsyncTask.delayHandler(req, resp, HttpMethod.DELETE);
        } else {
            resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
            resp.setStatus(HttpStatus.OK.value());
            resp.getWriter().write("default action for DELETE");
        }
    }
}
